package com.backend.modules.notification.service.impl;

import com.backend.modules.notification.service.EmailService;
import com.backend.modules.system.entity.SysUser;
import com.backend.modules.task.dto.FileAuditResult;
import com.backend.modules.task.entity.Task;
import com.backend.modules.task.entity.TaskSubmission;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    @Value("${spring.application.name:高校文档收集系统}")
    private String systemName;

    /**
     * 发送AI审核不通过邮件
     */
    @Async
    @Override
    public void sendAIRejectionEmail(TaskSubmission submission, FileAuditResult auditResult) {
        try {
            SysUser student = submission.getStudent();
            Task task = submission.getTask();
            
            // 创建模板上下文
            Context context = new Context();
            context.setVariable("studentName", student.getRealName());
            context.setVariable("taskName", task.getName());
            context.setVariable("systemName", systemName);
            context.setVariable("reason", auditResult.getReason());
            
            // 添加文件要求和提交要求
            context.setVariable("fileRequirements", task.getFileRequirements());
            context.setVariable("submitRequirements", task.getSubmitRequirements());
            
            // 处理详细问题
            List<Map<String, String>> issues = null;
            if (auditResult.getIssues() != null && !auditResult.getIssues().isEmpty()) {
                issues = auditResult.getIssues().stream().map(issue -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("fileName", issue.getFileName() != null ? issue.getFileName() : "未指定");
                    map.put("description", issue.getDescription());
                    map.put("severity", translateSeverity(issue.getSeverity()));
                    return map;
                }).collect(Collectors.toList());
            }
            context.setVariable("issues", issues);
            
            // 处理修改建议
            context.setVariable("suggestions", auditResult.getSuggestions());
            
            // 处理邮件链接
            String submissionUrl = String.format("/student/task/%d/submission", task.getId());
            context.setVariable("submissionUrl", submissionUrl);
            
            // 使用模板生成邮件内容
            String emailContent = templateEngine.process("email/ai-rejection", context);
            
            // 发送邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail, systemName);
            helper.setTo(student.getEmail());
            helper.setSubject("【" + systemName + "】任务《" + task.getName() + "》审核不通过");
            helper.setText(emailContent, true);
            
            mailSender.send(message);
            log.info("发送AI审核不通过邮件成功: {}", student.getEmail());
            
        } catch (Exception e) {
            log.error("发送AI审核不通过邮件失败", e);
        }
    }
    
    /**
     * 翻译严重程度
     */
    private String translateSeverity(String severity) {
        if (severity == null) {
            return "一般";
        }
        
        switch (severity.toLowerCase()) {
            case "error":
                return "高";
            case "warning":
                return "中";
            case "info":
                return "低";
            default:
                return severity;
        }
    }

    /**
     * 发送教师审核不通过邮件
     */
    @Async
    @Override
    public void sendTeacherRejectionEmail(TaskSubmission submission) {
        try {
            SysUser student = submission.getStudent();
            Task task = submission.getTask();
            
            // 创建模板上下文
            Context context = new Context();
            context.setVariable("studentName", student.getRealName());
            context.setVariable("taskName", task.getName());
            context.setVariable("systemName", systemName);
            context.setVariable("reason", submission.getReviewComment());
            
            // 处理邮件链接
            String submissionUrl = String.format("/student/task/%d/submission", task.getId());
            context.setVariable("submissionUrl", submissionUrl);
            
            // 使用模板生成邮件内容
            String emailContent = templateEngine.process("email/teacher-rejection", context);
            
            // 发送邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail, systemName);
            helper.setTo(student.getEmail());
            helper.setSubject("【" + systemName + "】任务《" + task.getName() + "》审核不通过");
            helper.setText(emailContent, true);
            
            mailSender.send(message);
            log.info("发送教师审核不通过邮件成功: {}", student.getEmail());
            
        } catch (Exception e) {
            log.error("发送教师审核不通过邮件失败", e);
        }
    }
} 